package com.gh.ssyx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.ssyx.mapper.RoleMapper;
import com.gh.ssyx.model.acl.AdminRole;
import com.gh.ssyx.model.acl.Role;
import com.gh.ssyx.service.AdminRoleService;
import com.gh.ssyx.service.RoleService;
import com.gh.ssyx.vo.acl.RoleQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author Eric Fang
 * @date 2023/6/18 14:48
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private AdminRoleService adminRoleService;

    @Override
    public IPage<Role> getPageList(RoleQueryVo roleQueryVo, Page<Role> pageParam) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        String roleName = roleQueryVo.getRoleName();
        if (!StringUtils.isEmpty(roleName)) {
            wrapper.like(Role::getRoleName, roleName);
        }
        Page<Role> page = baseMapper.selectPage(pageParam, wrapper);
        return page;
    }

    @Override
    public Map<String, Object> getRoles(Long adminId) {
        Map<String, Object> map = new HashMap<>();
        //所有角色
        List<Role> roleList = baseMapper.selectList(null);
        //为用户已分配的角色
        LambdaQueryWrapper<AdminRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminRole::getAdminId, adminId);
        List<Long> roleIds = adminRoleService.list(queryWrapper)
                .stream()
                .map(item -> item.getRoleId())
                .collect(Collectors.toList());
        List<Role> assignRoles = new ArrayList<>();
        for (Role role : roleList) {
            if (roleIds.contains(role.getId())) {
                assignRoles.add(role);
            }
        }
        map.put("allRolesList", roleList);
        map.put("assignRoles", assignRoles);
        return map;
    }

    @Override
    public void saveAdminRole(Long adminId, Long[] roleIds) {
        //删除用户已经分配过的角色
        LambdaQueryWrapper<AdminRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminRole::getAdminId, adminId);
        adminRoleService.remove(queryWrapper);
        //重新添加角色
        List<AdminRole> list = new ArrayList<>();
        for (Long roleId : roleIds) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(adminId);
            adminRole.setRoleId(roleId);
            list.add(adminRole);
        }
        adminRoleService.saveBatch(list);
    }
}
